package com.hspedu.seckill.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.UserService;
import com.hspedu.seckill.vo.RespBean;
import com.hspedu.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 自定义拦截器，处理秒杀接口限流
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求所对应的处理器对象是否是方法
        if (handler instanceof HandlerMethod) {

            User user = this.getUser(request, response);
            //将user设置到ThreadLocal
            UserContext.setUser(user);
            HandlerMethod hm = (HandlerMethod) handler;


            //得到AccessLimit注解
            AccessLimit methodAnnotation = hm.getMethodAnnotation(AccessLimit.class);

            //判断该方法是否有AccessLimit注解，没有就直接放行
            if (null == methodAnnotation) {
                return true;
            }

            int count = methodAnnotation.count();
            int seconds = methodAnnotation.seconds();

            //没有登录，进行拦截
            if (methodAnnotation.needLogin() && null == user) {
                render(response, RespBean.error(RespBeanEnum.SESSION_ERROR));
                return false;
            }


            //获取请求的uri
            String uri = request.getRequestURI();
            //获取redis该用户方法这个请求地址的次数
            Integer reidsCount = (Integer) redisTemplate.opsForValue().get(uri + ":" + user.getId());


            //如果没有访问过就初始化redis该用户方法这个请求地址的次数为1，过期时间设置为5s
            if (null == reidsCount) {
                redisTemplate.opsForValue().set(uri + ":" + user.getId(), 1, seconds, TimeUnit.SECONDS);
            } else if (reidsCount < count) {
                //将redis该用户方法这个请求地址的次数加1
                redisTemplate.opsForValue().increment(uri + ":" + user.getId());
            } else {//如果5秒内该用户的访问次数大于5就提示频繁访问
                render(response, RespBean.error(RespBeanEnum.ACCESS_LIMIT_REACHED));
                return false;
            }

        }
        return true;
    }

    //构建获取user对象方法
    public User getUser(HttpServletRequest request, HttpServletResponse response) {
        return userService.getUserByCookie(request, response);
    }

    //构建返回对象
    public void render(HttpServletResponse response, RespBean respBean) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        //将RespBean转成json字符串返回
        String error = new ObjectMapper().writeValueAsString(respBean);
        writer.print(error);
        writer.flush();
        writer.close();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
